package com.example.databasetest;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        MyDatabaseHelper dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 2);

        Button btn = findViewById(R.id.create_db);
        btn.setOnClickListener(v -> {
            dbHelper.getWritableDatabase();
        });

        Button addData = findViewById(R.id.add_data);
        addData.setOnClickListener(v -> {
            SQLiteDatabase db = dbHelper.getWritableDatabase();
            ContentValues values = new ContentValues();
            values.put("name", "The Da Vinci Code");
            values.put("author", "Dan Brown");
            values.put("price",16.96);
            values.put("pages",454);
            db.insert("Book",null, values);
            values.clear();

            values.put("name", "The Lost Symbol");
            values.put("author", "Dan Brown");
            values.put("price",19.95);
            values.put("pages",510);
            db.insert("Book", null, values);
        });

        Button queryBtn = findViewById(R.id.query_data);
        queryBtn.setOnClickListener(v -> {
            SQLiteDatabase db = dbHelper.getWritableDatabase();
            Cursor cursor = db.query("Book", null, null, null, null, null, null);

            if (cursor.moveToFirst()){
                do {

                    @SuppressLint("Range") String name = cursor.getString(cursor.getColumnIndex("name"));
                    @SuppressLint("Range") String author = cursor.getString(cursor.getColumnIndex("author"));
                    @SuppressLint("Range") int pages = cursor.getInt(cursor.getColumnIndex("pages"));
                    @SuppressLint("Range") double price = cursor.getFloat(cursor.getColumnIndex("price"));
                    Log.d(TAG, "name is " + name);
                    Log.d(TAG, "author is " + author);
                    Log.d(TAG, "pages is " + pages);
                    Log.d(TAG, "price is " + price);
                }while (cursor.moveToNext());
            }
        });
    }
}